Imports System.IO


Class TableInfo
    Public Name As String
    Public Key As New FieldInfo("RECORDID", "int", allowsNull:=False)
    Public Fields As New List(Of FieldInfo)

    Public Sub New()
        Key.Type = "int"
    End Sub

    Public Sub WriteDrop(ByVal tw As TextWriter)
        tw.WriteLine("DROP TABLE " & Name)
    End Sub

    Public Sub WriteCreate(ByVal tw As TextWriter)

        tw.WriteLine(String.Format("CREATE TABLE {0} (", Name))
        tw.Write(Key.FieldClause & " PRIMARY KEY")

        For j = 0 To Fields.Count - 1
            tw.WriteLine(",")
            tw.Write(Fields(j).FieldClause)
        Next
        tw.WriteLine(");")
    End Sub

    Public Sub WriteMultiInsert(ByVal tw As TextWriter)
        tw.Write(String.Format("INSERT INTO {0} ({1}", Name, Key.Name))
        For j = 0 To Fields.Count - 1
            tw.Write("," & Fields(j).FieldSql)
        Next
        tw.WriteLine(") VALUES")
        For i = 0 To Key.Rows.Count - 1
            tw.Write("(" & Key.Rows(i))
            For j = 0 To Fields.Count - 1
                tw.Write("," & Fields(j).Value(i))
            Next
            tw.WriteLine("),")
        Next
    End Sub

    Public Sub WriteInserts(ByVal tw As TextWriter)
        Dim header As New System.Text.StringBuilder

        header.Append(String.Format("INSERT INTO {0} ({1}", Name, Key.Name))
        For j = 0 To Fields.Count - 1
            header.Append("," & Fields(j).FieldSql)
        Next
        header.AppendLine(") VALUES")

        For i = 0 To Key.Rows.Count - 1
            tw.Write(header.ToString)
            tw.Write("(" & Key.Rows(i))
            For j = 0 To Fields.Count - 1
                tw.Write("," & Fields(j).Value(i))
            Next
            tw.WriteLine(");")
        Next
    End Sub

    Class InsertInfo
        Public Sql As String
        Public ReadOnly Data As New Dictionary(Of String, String)
    End Class

    Public Function GetInserts() As List(Of InsertInfo)
        Dim result As New List(Of InsertInfo)
        Dim info As InsertInfo
        Dim header As New System.Text.StringBuilder
        Dim tw As New System.Text.StringBuilder

        header.Append(String.Format("INSERT INTO {0} ({1}", Name, Key.Name))
        For j = 0 To Fields.Count - 1
            header.Append("," & Fields(j).FieldSql)
        Next
        header.AppendLine(") VALUES")

        For i = 0 To Key.Rows.Count - 1
            info = New InsertInfo
            tw.Length = 0
            tw.Append(header.ToString)
            tw.Append("(" & Key.Rows(i))
            For j = 0 To Fields.Count - 1
                info.Data.Add(Fields(j).Name, Fields(j).Value(i))
                tw.Append("," & Fields(j).Value(i))
            Next
            tw.Append(")")
            info.Sql = tw.ToString

            result.Add(info)
        Next
        Return result
    End Function

End Class
